//
//  ReadingMeterTaskViewController.swift
//  Employee
//
//  Created by tancheng on 2018/6/23.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftDate
import RxSwift
import Moya

class ReadingMeterTaskViewController: BaseVC {

    var isFunction = true //是否是功能入口
    
    var isCurrentMonth = true //是否是当月
    
    var parantVC: UIViewController?
    
    //
    lazy var tableView: UITableView = {
        
        let tabV = UITableView(frame: CGRect.zero, style: .plain)
        tabV.tableFooterView = UIView(frame: CGRectMake(0, 0, UIScreen.width, 10))
        tabV.backgroundColor = GlobalConfig.pageColor
        tabV.dataSource = self
        tabV.delegate = self
        tabV.separatorStyle = .none
        tabV.register(UINib.init(nibName: "ReadingMeterTaskCell", bundle: nil), forCellReuseIdentifier: ReadingMeterTaskCell.reuseIdentifer)
        
        tabV.mj_header = CustomRefreshHeader(refreshingBlock: { [weak self] in self?.updateData(by: true) })
        tabV.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: { [weak self] in
            self?.updateData(by: false)
        })
        tabV.mj_footer.isHidden = true
        return tabV
    }()
    
    var taskData:[ReadingMeterTaskModel] = []
    
    var send:ReadingMeterTaskSend = ReadingMeterTaskSend()
    var pager = PageModel()
    
    
    fileprivate var isAppear = false
    fileprivate var noDataV: NoDataV?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        if !isFunction {
           tableView.mj_header.beginRefreshing()
        }
   
        NotificationCenter.default.addObserver(self, selector: #selector(offLineUpdate), name: NSNotification.Name.offLine.updateReadingTask, object: nil)
        
        
    }
    
    
    @objc func offLineUpdate () {
        updateData(by: true)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setupUI() {
        title = "移动抄表"
        
        tableView.frame = CGRectMake(0, 0, UIScreen.width,  UIScreen.noNavBarHeight)
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
            make.right.left.equalToSuperview()
        }
        
        if #available(iOS 11, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        
        guard isFunction else {
            return
        }
        
        let dateStr = Date().string(custom: "yyyy-MM")
        send.meterReadDate = dateStr
        
    }
    

    
    //
    fileprivate func noData() {
        
        if noDataV != nil {
            self.tableView.addSubview(noDataV!)
            return
        }
        
        let frame = CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height)
        noDataV = NoDataV(frame: frame)
        noDataV?.image = UIImage(named: "bg-01")!
        
        let typeString = "暂无抄表安排"
        
        noDataV?.topTipText = typeString
        if let tempV = noDataV { self.tableView.addSubview(tempV) }
    }
    //数据刷新
   @objc func updateData(by isHeader: Bool = false) {
    
    
    
        send.pageIndex = isHeader ? pager.headerPage : pager.nextPage
        send.pageSize = pager.size
    
        if !isFunction {
            send.type = true
        }
    
        print(send)
    
        MeterRequest.shared.getReadingMeterTaskList(send: send, success: { (data, page) in
            
            self.pager = page
            
            self.isAppear = true//
            
            runOnMainThread {
                if isHeader {
                    
                    self.taskData = data
                    self.tableView.mj_header.endRefreshing()
                    
                }else {
                
                    self.taskData += data
                    self.tableView.mj_footer.endRefreshing()
                }
                
                // 分页判断
                self.tableView.mj_footer.isHidden = !self.pager.hasNextPage
                
                self.tableView.reloadData()
                
                if data.isEmpty {//是否有数据
                    self.noData()
                    return
                } else {
                    if let _ = self.noDataV?.superview {
                        
                        if let nv = self.noDataV {
                            nv.removeFromSuperview()
                            self.noDataV = nil
                        }
                        
                    }
                }
                
                
            }
            //
            }) {
        
                if isHeader {
                    runOnMainThread {
                        self.tableView.mj_header.endRefreshing()
                        
                      //是否有数据
                        if self.noDataV == nil {
                            self.noData()
                        }
                        
                    }
                }else {
                    runOnMainThread {
                         self.tableView.mj_footer.endRefreshing()
                    }
                   
                }
        }
    
    }

   

}





extension ReadingMeterTaskViewController: UITableViewDataSource,UITableViewDelegate {
    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return taskData.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return taskData[indexPath.row].cooperation ? 116+5 : 92+5
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 11
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: ReadingMeterTaskCell.reuseIdentifer, for: indexPath) as! ReadingMeterTaskCell
        
        cell.model = taskData[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = ReadingMeterDetailVC()
        
        vc.taskId = taskData[indexPath.row].taskId
        
        vc.listModel = taskData[indexPath.row]
        
        vc.completionClosure = {[weak self] in
            self?.updateData(by: true)
        }
        //离线删除
        vc.offLineCompletionClosure = {[weak self] in
            self?.taskData.remove(at: indexPath.row)
            self?.tableView.deleteRows(at: [indexPath], with: .automatic)
        }
        
        if parantVC != nil {
           parantVC?.navigationController?.pushViewController(vc, animated: true)
            return
        }
        
       
        navigationController?.pushViewController(vc, animated: true)
        
    }
    

}

extension ReadingMeterTaskViewController: SWXCPageViewDelegate {
    
    func reloadPageView(index: Int) {
        if !isAppear {
            
            let dateStr = "\(Date().year)" + "-" + String(format: "%02d",index+1)
            send.meterReadDate = dateStr
            
            tableView.mj_header.beginRefreshing()
            
        }
       
    }
    
    
}

